<template>
  <Dialog
    ref="dialog"
    title="下载报告"
    width="600"
    :hideClose="false"
    :closeOnClickModal="false"
  >
    <template #icon>
      <div>
        <el-icon size="24" style="cursor: pointer" @click="closeDialog">
          <Close />
        </el-icon>
      </div>
    </template>
    <!-- 当报告可以下载时 -->
    <div v-if="canDownload" class="" style="font-size: 14px">
      <div style="color: #333">请点击下载报告。</div>
      <div style="color: #888">
        (注：如遇浏览器拦截无法下载，请选择允许下载。)
      </div>
    </div>

    <!-- 当报告正在生成时 -->
    <div v-else class="" style="font-size: 14px; margin-bottom: 30px">
      <div
        v-if="isLoading"
        v-loading="isLoading"
        style="width: 100%; height: 50px"
      ></div>
      <div style="color: #333; text-align: center; margin-top: 20px">
        报告正在生成中,大约需要1～3分钟。
      </div>
    </div>

    <!-- 下载按钮 -->
    <div v-if="canDownload" class="right" style="margin: 30px 0">
      <el-button color="#004cf7" @click="downloadData(1)">下载图片</el-button>
      <el-button color="#004cf7" @click="downloadData(2)">下载PDF</el-button>
    </div>
  </Dialog>
</template>

<script setup>
import Dialog from '@/components/Dialog/Dialog.vue';
import { ref } from 'vue';
import { judgeExport } from '@/api/manage/manage.js';
import { ElMessage } from 'element-plus';

const judgeInfo = ref({}); // 存储报告信息
const dialog = ref(); // 弹窗引用
const isLoading = ref(false); // 加载状态
const canDownload = ref(true); // 是否允许下载
let pollingInterval = null; // 轮询定时器

// 点击下载报告按钮
const downloadData = async (type) => {
  // 启动加载状态
  isLoading.value = true;

  // 定义下载报告的文件名
  const fileName = type === 2 ? '测评报告.pdf' : '测评报告.jpg';
  const data = {
    id: judgeInfo.value.id,
    type,
  };

  // 定义轮询函数
  const pollDownloadData = async () => {
    try {
      const res = await judgeExport(data, { timeout: 120000 });

      if (res.code == 20000) {
        // 如果接口返回了有效的下载链接
        if (res.data?.url) {
          isLoading.value = false; // 结束加载状态
          canDownload.value = true; // 显示下载按钮
          clearInterval(pollingInterval); // 停止轮询
          await downloadBlob(res.data.url, fileName); // 下载文件
        }
      } else if (res.data.code == 400333) {
        // 如果接口返回 400333，表示报告还在生成中，继续轮询
        isLoading.value = true;
        canDownload.value = false; // 隐藏下载按钮
      }
    } catch (error) {
      console.error('下载失败:', error);
      isLoading.value = false;
    }
  };

  // 每20秒轮询一次，直到获得有效的下载链接
  pollingInterval = setInterval(pollDownloadData, 20000);

  // 初始化轮询，立即执行一次
  await pollDownloadData();
};

// 下载 Blob 数据
const downloadBlob = async (url, fileName) => {
  try {
    const blob = await fetch(url).then((res) =>
      res.ok ? res.blob() : Promise.reject(res)
    );
    const urlObject = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = urlObject;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    setTimeout(() => {
      window.URL.revokeObjectURL(urlObject);
      document.body.removeChild(a);
    }, 0);
    ElMessage({ message: '下载成功', type: 'success' });
  } catch (error) {
    console.log('下载失败:', error);
  }
};

// 打开弹窗时的处理函数
const openChange = async (val) => {
  judgeInfo.value = val;
  canDownload.value = true; // 打开弹窗时默认允许下载
  dialog.value.openChange();
};

// 关闭弹窗时停止轮询
const closeDialog = () => {
  if (pollingInterval) {
    clearInterval(pollingInterval); // 关闭轮询
  }
  isLoading.value = false; // 停止加载状态
  dialog.value.closeChange();
};

defineExpose({
  openChange,
});
</script>

<style lang="scss" scoped>
:deep(.el-divider--horizontal) {
  margin: 10px 0;
}
</style>
